package de.hypoport.einarbeitung.scrumspirit;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import org.apache.wicket.protocol.http.WebApplication;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.apache.wicket.spring.injection.annot.SpringComponentInjector;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;


/**
 * Application object for your web application. If you want to run this application without deploying, run the Start class.
 *
 * @see wicket.myproject.Start#main(String[])
 */
public class WicketApplication extends WebApplication
{

	@SpringBean
	private EntityManagerFactory entityManagerFactory;

	@SpringBean
	private EntityManager entityManager;

	@SpringBean
	private PlatformTransactionManager transactionManager;


    /**
     * Constructor
     */
	public WicketApplication()
	{
	}

	public EntityManagerFactory getEntityManagerFactory() {
		return entityManagerFactory;
	}

	public void setEntityManagerFactory(
			EntityManagerFactory entityManagerFactory) {
		this.entityManagerFactory = entityManagerFactory;
	}

	public EntityManager getEntityManager() {
		return entityManager;
	}

	public void setEntityManager(EntityManager entityManager) {
		this.entityManager = entityManager;
	}

	public PlatformTransactionManager getTransactionManager() {
		return transactionManager;
	}

	public void setTransactionManager(
			PlatformTransactionManager transactionManager) {
		this.transactionManager = transactionManager;
	}

	/**
	 * @see wicket.Application#getHomePage()
	 */
	@Override
	public Class<HomePage> getHomePage()
	{
		return HomePage.class;
	}

	@Override
	protected void init() {

		this.addComponentInstantiationListener(new SpringComponentInjector(this));


		if (null == entityManagerFactory) {
			entityManagerFactory = Persistence
					.createEntityManagerFactory("eclipseLinkFile");
		}

		if (null == entityManager) {
			entityManager = entityManagerFactory.createEntityManager();
		}

		if (null == transactionManager) {
			transactionManager = new JpaTransactionManager(
					this.entityManagerFactory);
		}

	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		transactionManager.notifyAll();
		entityManager.close();
		this.entityManagerFactory.close();
	}

}
